package com.vanward.mes.scan.service.impl;

import com.vanward.mes.scan.dto.BatchScanRequestDTO;
import com.vanward.mes.scan.dto.BatchScanResultDTO;
import com.vanward.mes.scan.dto.ScanResultDTO;
import com.vanward.mes.scan.dto.WorkOrderStatsDTO;
import com.vanward.mes.scan.dto.WorkshopLineTreeDTO;
import com.vanward.mes.scan.mapper.LotMapper;
import com.vanward.mes.scan.service.ScanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.vanward.mes.scan.entity.Lot;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * 扫码服务实现类
 */
@Service
public class ScanServiceImpl implements ScanService {
    
    private static final Logger logger = LoggerFactory.getLogger(ScanServiceImpl.class);

    @Autowired
    private LotMapper lotMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ScanResultDTO processScan(String barcode, String scanType, String lineId) {
        // 创建响应对象
        ScanResultDTO result = new ScanResultDTO();
        result.setSuccess(false);
        
        // 参数验证
        if (!StringUtils.hasText(barcode)) {
            result.setErrorMsg("条码不能为空");
            return result;
        }
        
        // 标准化扫码类型（IN或OUT）
        String normalizedScanType = (scanType == null || !scanType.equalsIgnoreCase("IN")) ? "OUT" : "IN";
        result.setScanType(normalizedScanType);
        
        try {
            // 1. 查询条码信息
            ScanResultDTO lotInfo = lotMapper.selectLotInfoByBarcode(barcode);
            if (lotInfo == null) {
                result.setErrorMsg("未找到条码信息");
                return result;
            }
            
            // 2. 根据扫码类型进行重复扫码校验
            // 2.1 查询批次的详细信息，包括开始和结束时间
            Lot lotDetail = lotMapper.selectById(lotMapper.selectIdByBarcode(barcode));
            
            if ("OUT".equals(normalizedScanType)) {
                // 下线扫码：检查是否已经下线（endTime不为null）
                if (lotDetail != null && lotDetail.getEndTime() != null) {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    result.setErrorMsg("条码已经在" + dateFormat.format(lotDetail.getEndTime()) + "下线，切勿重复扫码");
                    return result;
                }
                
                // 下线扫码逻辑
                int lotUpdateCount = lotMapper.updateLotEndTimeAndStatus(barcode);
                if (lotUpdateCount == 0) {
                    result.setErrorMsg("更新批次结束时间失败");
                    return result;
                }
                
                // 更新工单完成数量和状态
                lotMapper.updateWorkOrderFinishedQty(barcode);
                lotMapper.updateWorkOrderStatus(barcode);
                
                // 插入批次完工记录
                lotMapper.insertLotFinishedLog(barcode);
                
                // 插入事件记录（下线扫码）
                lotMapper.insertEvent(barcode);
                
            } else {
                // 上线扫码：检查是否已经上线（startTime不为null）
                if (lotDetail != null && lotDetail.getStartTime() != null) {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    result.setErrorMsg("条码已经在" + dateFormat.format(lotDetail.getStartTime()) + "上线，切勿重复扫码");
                    return result;
                }
                
                // 上线扫码逻辑
                int lotUpdateCount = lotMapper.updateLotStartTimeAndStatus(barcode);
                if (lotUpdateCount == 0) {
                    result.setErrorMsg("更新批次开始时间失败");
                    return result;
                }
                
                // 插入事件记录（上线扫码）
                lotMapper.insertEvent(barcode);
            }
            
            // 设置成功结果
            result.setLotNo(lotInfo.getLotNo());
            result.setPartCode(lotInfo.getPartCode());
            result.setPartName(lotInfo.getPartName());
            result.setDrawingNo(lotInfo.getDrawingNo());
            result.setLineCode(lotInfo.getLineCode());
            result.setLineName(lotInfo.getLineName());
            result.setWoNo(lotInfo.getWoNo());
            
            result.setSuccess(true);
            
        } catch (Exception e) {
            // 捕获异常并设置错误信息
            result.setErrorMsg("扫码处理失败: " + e.getMessage());
            logger.error("扫码处理异常: {}", e.getMessage(), e);
        }
        
        return result;
    }
    
    @Override
    public WorkOrderStatsDTO getWorkOrderStats(String barcode) {
        logger.info("获取工单统计信息，条码：{}", barcode);
        
        try {
            // 参数验证
            if (!StringUtils.hasText(barcode)) {
                logger.warn("条码为空");
                return new WorkOrderStatsDTO(0, 0, 0); // 返回空统计
            }
            
            // 查询工单统计信息
            WorkOrderStatsDTO stats = lotMapper.selectWorkOrderStatsByBarcode(barcode);
            if (stats != null) {
                logger.info("工单统计查询成功，条码：{}", barcode);
                return stats;
            } else {
                logger.warn("未找到条码对应的工单统计信息，条码：{}", barcode);
                return new WorkOrderStatsDTO(0, 0, 0); // 返回空统计
            }
        } catch (Exception e) {
            logger.error("获取工单统计信息失败：{}", e.getMessage(), e);
            return new WorkOrderStatsDTO(0, 0, 0); // 异常时返回空统计
        }
    }
    
    @Override
    public List<WorkshopLineTreeDTO> selectWorkshopLineTree() {
        logger.info("查询车间产线树结构");
        try {
            return lotMapper.selectWorkshopLineTree();
        } catch (Exception e) {
            logger.error("查询车间产线树结构失败：{}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BatchScanResultDTO processBatchScan(BatchScanRequestDTO request) {
        BatchScanResultDTO result = new BatchScanResultDTO();
        List<ScanResultDTO> details = new ArrayList<>();
        int successCount = 0;
        int failedCount = 0;

        // 参数验证
        if (request == null || request.getBarcodes() == null || request.getBarcodes().isEmpty()) {
            result.setSuccess(false);
            result.setSuccessCount(0);
            result.setFailedCount(0);
            result.setTotalCount(0);
            result.setDetails(details);
            return result;
        }

        // 遍历每个条码进行处理
        for (String barcode : request.getBarcodes()) {
            ScanResultDTO scanResult = processScan(barcode, request.getScanType(), request.getLineId());
            details.add(scanResult);
            
            if (scanResult.isSuccess()) {
                successCount++;
            } else {
                failedCount++;
            }
        }

        // 设置批量处理结果
        result.setSuccess(true); // 批量操作整体成功（即使个别条码失败）
        result.setSuccessCount(successCount);
        result.setFailedCount(failedCount);
        result.setTotalCount(request.getBarcodes().size());
        result.setDetails(details);

        return result;
    }
}
